/**
http://geocld.github.io/2016/03/10/javascript_plugin/
https://blog.csdn.net/mxlwx123/article/details/52354089
*/
(function(global) {
	var options = {};
	var root;
	var tree;
	var svg;
	var node;
	var link;
	var api = function(opts) {
		//没有参数传入，直接返回默认参数
		if (opts!=null) {
			//有参数传入，通过key将options的值更新为用户的值
			for (var key in opts) {
				options[key] = opts[key];
			}
		}
	};
	api.prototype = {
		//Tree
		tree: function() {
			var _self = this;
			var width = window.innerWidth-20,
			height = window.innerHeight-20;

			tree = d3.layout.tree().size([width - 20, height - 20]);

			root = {};
			nodes = tree(root);

			root.parent = root;
			//root.px = root.x;
			//root.py = root.y;
			var body="body";
            if(options['id']){
            	body="#"+options['id'];
            }
			svg = d3.select(body).append("svg").attr("width", width).attr("height", height).append("g").attr("transform", "translate(10,10)");
			node = svg.selectAll(".node");
			link = svg.selectAll(".link");

			_self.updateTree();

		},
		addNode: function() {
			// Add a new node to a random parent.
			var n = {
				id: nodes.length
			},
			p = nodes[Math.random() * nodes.length | 0];
			if (p.children) p.children.push(n);
			else p.children = [n];
			nodes.push(n);
		},
		updateTree: function() {
			var diagonal = d3.svg.diagonal();

			// Recompute the layout and data join.
			node = node.data(tree.nodes(root),
			function(d) {
				return d.id;
			});
			link = link.data(tree.links(nodes),
			function(d) {
				return d.source.id + "-" + d.target.id;
			});

			// Add entering nodes in the parent’s old position.
			node.enter().append("circle").attr("class", "node").attr("r", 4).attr("cx",
			function(d) {
				return d.parent.x;
			}).attr("cy",
			function(d) {
				return d.parent.y;
			});

			// Add entering links in the parent’s old position.
			link.enter().insert("path", ".node").attr("class", "link").attr("d",
			function(d) {
				var o = {
					x: d.source.x,
					y: d.source.y
				};
				return diagonal({
					source: o,
					target: o
				});
			});

			// Transition nodes and links to their new positions.
			var t = svg.transition()
			//.duration(duration);
			t.selectAll(".link").attr("d", diagonal);

			t.selectAll(".node").attr("cx",
			function(d) {
				return d.x = d.x;
			}).attr("cy",
			function(d) {
				return d.y = d.y;
			});
		},
		//Table
		table:function(){
			var data = [["id", "name", "sex"], [1, "cike", "男"], [2, "xiao", "女"]];
			var th = d3.select("thead").selectAll("th").data(data[0]).enter().append("th").text(function(d) {
				return d;
			});
			data.shift();
			var tr = d3.select("tbody").selectAll("tr").data(data).enter().append("tr");
			var td = tr.selectAll("td").data(function(d) {
				return d;
			}).enter().append("td").text(function(d) {
				return d;
			});
		}
	}
	global.chart = api;
})(this)
